<?php

use framework\support\Request;
use framework\support\Response;
use framework\support\Db;
use framework\support\Redis;
use framework\libraries\Utils;

class admin
{

    function _checkToke()
    {
        $token = Request::header("Authorization");
        $arr = explode(" ", $token);
        $key = $arr[count($arr) - 1];
        return Redis::get("admin_" . $key);
    }

    function code_get()
    {
        if (!$this->_checkToke()) {
            return Response::Error(401, "令牌过期");
        }
        $code = md5(Utils::random_string('alnum', 32));
        $expire = Request::get("days");
        if ($expire) {
            $date = date("Y-m-d H:i:s", strtotime("+{$expire} days"));
        } else {
            $expire = Request::get("hours");
            if ($expire) {
                $date = date("Y-m-d H:i:s", strtotime("+{$expire} hours"));
            }
        }
        $data = [
            'code' => $code,
            'expire_time' => $date,
        ];
        $id = Db::insert("code", $data);
        if ($id) {
            Response::Success($code);
        } else {
            Response::Error(40401, "生成错误");
        }
    }

    function login_post()
    {
        $userName = Request::post("username");
        $password = Request::post("password");
        if ($userName != "admin" && $password = "123456") {
            return Response::Error(401, "登录失败");
        }
        $token = md5(Utils::random_string('alnum', 32));
        Redis::setEx('admin_' . $token, 86400 * 3, true);
        return Response::Success($token);
    }

    function use_total_get()
    {
        $count = Db::count("code", [
            "used_time[>]" => '2024-10-01',
        ]);
        return Response::Success($count);
    }
}
